﻿#region Usings
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using InsuranceAdjuster;
using InsuranceAdjuster.Helpers;
using InsuranceAdjuster.OccasionallyConnected;
using InsuranceAdjuster.OccasionallyConnected.Messages;
using InsuranceAdjuster.Services;
using InsuranceAdjuster.Web.Models;
using Papa.Common;
#endregion

namespace InsuranceAdjuster.ViewModels {
    public class ClaimViewModel : ViewModelBase<Claim> {

        private void OnSaveClaim() {
            EntityManager.ProcessMessage(new SaveClaimMessage(Model, ViewModelId));
        }

        protected override void RegisterCommands() {
            SaveClaimCommand = new RelayCommand(OnSaveClaim, () =>
                Model != null &&
                Model.ValidationErrors.Any() == false);
        }

        protected override void OnMessageCompleted(Message message) {
            if (message.CallerGuid == ViewModelId
                && message is SaveClaimMessage) {

                if (message.Status == MessageStatus.Completed) {
                    var ThisMessage = message as SaveClaimMessage;
                    var DialogText = String.Empty;
                    if (ThisMessage.HasError)
                        DialogText = String.Format("Saving Claim {0} was unsuccessful", Model.ClaimNumber);
                    else
                        DialogText = String.Format("Saving Claim {0} was successful", Model.ClaimNumber);

                    var MyDialogMessage = new DialogMessage(DialogText, result => {
                    });
                    Messenger.Default.Send<DialogMessage>(MyDialogMessage);
                }

                message.Clear();
            }
        }


        #region Initialization
        public ObservableCollection<State> States { get; private set; }
        public ObservableCollection<ClaimStatu> ClaimStatusColl { get; private set; }
        public VinHelper VinHelper { get; private set; }
        public RelayCommand SaveClaimCommand { get; set; }

        public ClaimViewModel(IPageConductor pageConductor) {
            PageConductor = pageConductor;
            RegisterCommands();

            // Initialize collections
            States = new ObservableCollection<State>();
            ClaimStatusColl = new ObservableCollection<ClaimStatu>();
            VinHelper = new VinHelper();

            // Get required reference data
            EntityManager.ProcessMessage(new GetClaimStatusesMessage());
            EntityManager.ProcessMessage(new GetStatesMessage());
        }

        private void OnPropertyChanged(string propertyName) {
            switch (propertyName) {
                case "States":
                    if (Model != null && String.IsNullOrEmpty(Model.InsuredState) && States.Count > 0)
                        Model.InsuredState = States[0].StateCode;
                    break;
            }
        }

        protected override void LoadNewModel() {
            throw new NotSupportedException("ClaimViewModel does not support creating new claims");
        }
        protected override void LoadExistingModel(Guid entityGuid) {
            EntityManager.ProcessMessage(new GetClaimMessage(entityGuid));
        }
        protected override void OnNewModelAvailable(Claim currentModel, Claim newerModel) {
            VinHelper.SelectedClaim = newerModel;
            newerModel.PropertyChanged += (o, e) => SaveClaimCommand.RaiseCanExecuteChanged();

        }
        protected override void OnEntityChanged(Guid entityGuid, Type entityType, ChangeOperation changeOperation, Origin changeOrigin, IEntity entity) {
            if (entityType == typeof(State)) {
                if (States.Contains(entity as State) == false) {
                    States.Add(entity as State);
                    if (Model != null && String.IsNullOrEmpty(Model.InsuredState) == false) {
                        RaisePropertyChanged("Model");
                    }
                }
                RaisePropertyChanged("States");
            }

        }
        #endregion
    }
}
